{% extends "base.html" %}
{% load i18n %}
{% load static %}
{% block content %}
    <div id="content">

    <!-- Begin Page Content -->
    <div class="container-fluid">

        <!-- Page Heading -->
        <h1 class="h3 mb-2 text-gray-800">主机分组</h1>

        <!-- 模态框 -->
        <div class="modal fade" id="hostgroupModal" tabindex="-1" role="dialog" aria-labelledby="userModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
              <!-- 模态框头部 -->
              <div class="modal-header">
                <h5 class="modal-title" id="userModalLabel">主机分组</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <!-- 模态框主体内容 -->
              <div class="modal-body">
                <form>
                  <div class="form-group d-flex align-items-center">
                    <label for="input1" class="mr-3 w-25"><span class="text-danger">*</span>&nbsp;名称</label>
                    <input type="text" class="form-control w-75" id="input1" placeholder="请输入内容">
                  </div>
                  <div class="form-group d-flex align-items-center">
                    <label for="input5" class="mr-3 w-25"><span class="text-danger">*</span>&nbsp;描述</label>
                    <input type="text" class="form-control w-75" id="input5" placeholder="请输入描述">
                  </div>
                  <div style="display: none;">
                    <label for="input6" class="mr-3 w-25"></label>
                    <input type="text" class="form-control w-75" id="input6" placeholder="">
                  </div>
                    <hr class="sidebar-divider">
                    <div class="form-group">
                        <label for="inputType"><span class="text-danger">*</span>&nbsp;目标主机选择&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="exampleRadios" id="radio1" value="option1" checked onchange="switchInput()">
                            <label class="form-check-label" for="radio1">手动选择主机</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="exampleRadios" id="radio2" value="option2" onchange="switchInput()">
                            <label class="form-check-label" id="radio2Label" for="radio2">文件上传自动录入</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="exampleRadios" id="radio3" value="option3" onchange="switchInput()">
                            <label class="form-check-label" for="radio3">手动选择Salt Master</label>
                        </div>
                    </div>

                  <!-- SaltMaster双向选择框 -->
                  <div class="form-group" id="multiSelect" style="display: none;">
                    <div class="row">
                      <div class="col">
                          <label class="mr-5"><span class="text-danger">*</span>&nbsp;可选Salt Master: </label>
                        <select id="availableOptions" multiple class="form-control" style="height: 200px; background-color: white; color: black; text-align: left; border: 1px solid #ced4da;">
                          {% for each_user_salt_info in user_salt_info %}
                            <option value="{{ each_user_salt_info.id }}">{{ each_user_salt_info.name }}</option>
                            {% endfor %}
                        </select>
                      </div>
                        <div class="col-1 d-flex flex-column align-items-center justify-content-center">
                          <button type="button" class="btn btn-primary w-100" id="moveRight"><span class="ml-0">→</span></button>
                          <button type="button" class="btn btn-primary w-100 mt-2" id="moveLeft">←</button>
                        </div>
                      <div class="col">
                          <label class="mr-5"><span class="text-danger">*</span>&nbsp;已选Salt Master: </label>
                        <select id="selectedOptions" multiple class="form-control" style="height: 200px; background-color: white; color: black; text-align: left; border: 1px solid #ced4da;">
                          <!-- 已选择的项会显示在这里 -->
                        </select>
                      </div>
                    </div>
                  </div>

                  <!-- 主机双向选择框 -->
                  <div class="form-group" id="multiHostSelect">
                    <label for="dualListbox" class="mr-3 w-25">主机列表</label>
                    <div class="row">
                      <div class="col">
                        <!-- 搜索框 -->
                        <div class="input-group mb-2">
                            <input type="text" id="searchHostInput" class="form-control" placeholder="搜索可用主机" oninput="search_host()">
                                <div class="input-group-append">
                                    <button type="button" class="btn btn-primary" onclick="search_host()">
                                        <i class="fas fa-search fa-sm"></i>
                                    </button>
                                </div>
                        </div>
                        <select id="availableHostOptions" multiple class="form-control" style="height: 300px; background-color: white; color: black; text-align: left; border: 1px solid #ced4da;">
                          {% for each_hosts_limited in hosts_limited %}
                            <option value="{{ each_hosts_limited.id }}">{{ each_hosts_limited.name }}</option>
                            {% endfor %}
                        </select>
                      </div>
                        <div class="col-1 d-flex flex-column align-items-center justify-content-center">
                          <button type="button" class="btn btn-primary w-100" id="moveHostRight"><span class="ml-0">→</span></button>
                          <button type="button" class="btn btn-primary w-100 mt-2" id="moveHostLeft">←</button>
                        </div>
                      <div class="col">
                        <!-- 搜索框 -->
                        <div class="input-group mb-2">
                            <input type="text" id="searchSelectedHostInput" class="form-control" placeholder="搜索已选主机" oninput="search_selected_host()">
                                <div class="input-group-append">
                                    <button class="btn btn-primary" type="button">
                                        <i class="fas fa-search fa-sm"></i>
                                    </button>
                                </div>
                        </div>
                        <select id="selectedHostOptions" multiple class="form-control" style="height: 300px; background-color: white; color: black; text-align: left; border: 1px solid #ced4da;">
                          <!-- 已选择的项会显示在这里 -->
                        </select>
                      </div>
                    </div>
                  </div>

                    <!-- 文件上传框 -->
                    <div id="fileUploadDiv" style="display: none;">
                        <label for="inputType1"><span class="text-danger">*</span>&nbsp;执行方式&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="exampleRadios1" id="salt_hg" value="option1" checked onchange="switchType()">
                            <label class="form-check-label" for="salt_hg">SaltStack</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="exampleRadios1" id="an_hg" value="option2" onchange="switchType()">
                            <label class="form-check-label" for="an_hg">Ansible</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            <select id="an_master" class="form-control mt-6" style="width: 300px; height: auto; display: none;">
                                <option>请选择Ansible Master</option>
                                {% for each_user_an_info in user_an_info %}
                                <option value="{{ each_user_an_info.id }}">{{ each_user_an_info.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <br>
                        <br>
                        <div class="form-group row align-items-center">
                            <!-- 文件选择区域 -->
                            <div class="col-md-9">
                                <label for="fileUpload" class="sr-only">选择文件：</label>
                                <div class="custom-file">
                                    <input type="file" class="custom-file-input" id="fileUpload" onchange="showFileName()">
                                    <label class="custom-file-label" for="fileUpload">仅支持普通文本文件，以换行分割每条记录</label>
                                </div>
                            </div>
                            <!-- 上传按钮 -->
                            <div class="col-md-3 text-md-left mt-3 mt-md-0">
                                <button type="button" class="btn btn-primary w-100" id="uploadButton" onclick="uploadFile()" disabled>读取文件</button>
                            </div>
                        </div>
                        <!-- 显示文件名 -->
                        <div id="fileNameDisplay" class="mt-2" style="display: none;">
                            <p>已选择文件：<span id="fileName"></span></p>
                        </div>
                        <!-- 上传状态 -->
                        <div id="uploadStatus" style="margin-top: 10px; display: none;">
                            <p id="statusMessage"></p>
                        </div>
                    </div>


                </form>
                  <label class="mr-3 w-100">
                      <span id="msg" class="text-danger"></span>
                          <a id="hg_file" href="#" onclick="check_hg_file()"></a>
                  </label>
              </div>
              <!-- 模态框底部 -->
              <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="create_host_group()">提交</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 确认模态框 -->
        <div class="modal fade" id="confirmModal" tabindex="-1" role="dialog" aria-labelledby="confirmModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <!-- 模态框头部 -->
              <div class="modal-header">
                <h5 class="modal-title" id="confirmModalLabel">确认操作</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <!-- 模态框主体内容 -->
              <div class="modal-body">
                您确定要对主机分组<span id="hg_msg" class="text-danger">  </span>进行删除操作吗？该操作无法撤销
              </div>
              <div class="modal-body">
                <label class="mr-3 w-100"><span id="confirm_msg" class="text-danger"></span></label>
              </div>
              <!-- 模态框底部 -->
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmButton" onclick="del_host_group()">确认</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 分组主机模态框 -->
        <div class="modal fade" id="minionModal" tabindex="-1" role="dialog" aria-labelledby="confirmModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
              <!-- 模态框头部 -->
              <div class="modal-header">
                <h5 class="modal-title" id="minionModalLabel"><span id="hg_name"></span>&nbsp;主机组信息</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <!-- 模态框主体内容 -->
                    <div class="card shadow mb-8">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered" id="dataTable1" width="100%" cellspacing="0">
                                    <thead>
                                        <tr>
                                            <th>主机组名称</th>
                                            <th>包含主机/Salt Master</th>
                                        </tr>
                                    </thead>
                                    <tfoot>
                                        <tr>
                                            <th>主机组名称</th>
                                            <th>包含主机/Salt Master</th>
                                        </tr>
                                    </tfoot>
                                    <tbody id="table-body">
                                       <!-- 填充内容 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
              <!-- 模态框底部 -->
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
              </div>
            </div>
          </div>
        </div>

        <!-- DataTales Example -->
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <button id="add_salt" class="btn btn-primary btn-sm mr-2" onclick="clear_rowText()"> &nbsp;添&nbsp;加&nbsp; </button>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                        <thead>
                            <tr>
                                <th>名称</th>
                                <th>描述</th>
                                <th>主机数量</th>
                                <th>执行方式</th>
                                {% if request.user.is_superuser %}
                                    <th>创建人</th>
                                {% endif %}
                                <th>创建时间</th>
                                <th>更新时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tfoot>
                            <tr>
                                <th>名称</th>
                                <th>描述</th>
                                <th>主机数量</th>
                                <th>执行方式</th>
                                {% if request.user.is_superuser %}
                                    <th>创建人</th>
                                {% endif %}
                                <th>创建时间</th>
                                <th>更新时间</th>
                                <th>操作</th>
                            </tr>
                        </tfoot>
                        <tbody>
                            <tr style="display: none;">
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                {% if request.user.is_superuser %}
                                <td></td>
                                {% endif %}
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            {% for each_host_group in all_host_group %}
                            <tr id="tr-{{ each_host_group.id }}">
                                <td>{{ each_host_group.name }}</td>
                                <td>{{ each_host_group.description }}</td>
                                <td>{{ each_host_group.host_num }}</td>
                                <td>{{ each_host_group.get_type_display }}</td>
                                {% if request.user.is_superuser %}
                                    <td>{{ each_host_group.user.username }}</td>
                                {% endif %}
                                <td>{{ each_host_group.create_time }}</td>
                                <td>{{ each_host_group.update_time }}</td>
                                <td style="display: none;">{{ each_host_group.id }}</td>
                                <td>
                                    <button type="button" class="btn btn-info btn-sm" onclick="show_minions(this)" value="{{ each_host_group.name }}">详情</button>
                                    <button type="button" class="btn btn-primary btn-sm" onclick="get_rowText(this)" data-row-id="tr-{{ each_host_group.id }}" value="{{ each_host_group.name }}">编辑</button>
                                    <button type="button" class="btn btn-danger btn-sm" onclick="get_rowid(this)" id="{{ each_host_group.name }}">删除</button>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>
    <!-- /.container-fluid -->
    <div id="load" class="position-fixed w-100 h-100"
     style="top: 0; left: 0; background: rgba(255, 255, 255, 0.2); z-index: 1100; display: none;
            justify-content: center;
            align-items: center;">
        <div class="spinner-border text-success" role="status" style="width: 3rem; height: 3rem; position: absolute; top: 50%; left: 50%; margin-top: -1.5rem; margin-left: -1.5rem;">
        <span class="sr-only">加载中...</span>
    </div>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
{% endblock content %}
{% block js %}
    <script type="text/javascript">
        // 设置加载图片
        function loading() {
            document.getElementById('load').style.display = 'flex';
        };

        // 移除加载图片
        function loading_remove() {
            document.getElementById('load').style.display = 'none';
        };

        $(document).ready(function() {
            // 移动右侧按钮事件：将选中的项从左侧移动到右侧
            $('#moveRight').click(function() {
              $('#availableOptions option:selected').each(function() {
                $('#selectedOptions').append($(this));  // 将选中的项添加到右侧
              });
            });
            $('#moveHostRight').click(function() {
              $('#availableHostOptions option:selected').each(function() {
                $('#selectedHostOptions').append($(this));  // 将选中的项添加到右侧
              });
            });

            // 移动左侧按钮事件：将选中的项从右侧移动到左侧
            $('#moveLeft').click(function() {
              $('#selectedOptions option:selected').each(function() {
                $('#availableOptions').append($(this));  // 将选中的项添加到左侧
              });
            });
            $('#moveHostLeft').click(function() {
              $('#selectedHostOptions option:selected').each(function() {
                $('#availableHostOptions').append($(this));  // 将选中的项添加到左侧
              });
            });
          });

        window.addEventListener('load', function () {
            // 检查 DataTable 是否已经初始化
            if ($.fn.DataTable.isDataTable('#dataTable')) {
                $('#dataTable').DataTable().destroy(); // 销毁已有实例
            }
            // 初始化 DataTable
            $('#dataTable').DataTable({
                "order": [[3, 'desc']]
            });
        });

        // 移除reminder
        function reminder_remove() {
            var reminder_msg = document.getElementById("msg");
            reminder_msg.innerHTML = '';
        };

        // 是否隐藏选择Ansible Master
        function switchType() {
            const salt_hg = document.getElementById("salt_hg");

            if (salt_hg.checked) {
                an_master.style.display = "none";
            } else {
                an_master.style.display = "block";
            }
        }

        function switchInput() {
            const radio1 = document.getElementById("radio1");
            const multiHostSelect = document.getElementById("multiHostSelect");
            const radio2 = document.getElementById("radio2");
            const fileUploadDiv = document.getElementById("fileUploadDiv");
            const radio3 = document.getElementById("radio3");
            const multiSelect = document.getElementById("multiSelect");

            // 如果 radio1 被选中，显示 div；否则隐藏
            if (radio1.checked) {
                multiHostSelect.style.display = "block";
            } else {
                multiHostSelect.style.display = "none";
            }
            // 如果 radio2 被选中，显示 div；否则隐藏
            if (radio2.checked) {
                fileUploadDiv.style.display = "block";
            } else {
                fileUploadDiv.style.display = "none";
            }
            // 如果 radio3 被选中，显示 div；否则隐藏
            if (radio3.checked) {
                multiSelect.style.display = "block";
            } else {
                multiSelect.style.display = "none";
            }
        }

        function showFileName() {
            const fileInput = document.getElementById("fileUpload");
            const fileName = document.getElementById("fileName");
            const fileNameDisplay = document.getElementById("fileNameDisplay");
            const uploadButton = document.getElementById("uploadButton");

            if (fileInput.files.length > 0) {
                fileName.textContent = fileInput.files[0].name;
                fileNameDisplay.style.display = "block";
                uploadButton.disabled = false; // 启用上传按钮
            } else {
                fileNameDisplay.style.display = "none";
                uploadButton.disabled = true; // 禁用上传按钮
            }
        }

        //查看文件内容
        function check_hg_file() {
            var reminder_msg = document.getElementById("msg");
            $.ajax({
                type: "post",
                url: "/download_hg/",
                data: {
                    filename: document.querySelector('#hg_file').getAttribute('data-value'),
                },
                headers: {
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                complete: function () {
                },
                success: function (hg_content) {
                    var formattedContent = hg_content.replace(/\n/g, '<br>');
                    // 在新 tab 中打开文件内容
                    var newTab = window.open();
                    // 将文件内容写入新 tab
                    newTab.document.write(formattedContent);
                    // 关闭文档流，完成加载
                    newTab.document.close();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reminder_msg.innerHTML = 'Reminder: ' + errorThrown;
                }
            });
        }

        function uploadFile() {
            var reminder_msg = document.getElementById("msg");
            var hg_file = document.getElementById("hg_file");
            const uploadStatus = document.getElementById("uploadStatus");
            const statusMessage = document.getElementById("statusMessage");

            var upload_hg_executed = "0";
            if (an_hg.checked) {
              upload_hg_executed = "1";
            }

            let fileInput = $('#fileUpload')[0].files[0];  // 获取文件
            let formData = new FormData();
            formData.append('file', fileInput);
            formData.append('upload_hg_executed', upload_hg_executed);

            $.ajax({
                url: '/read_file/',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                beforeSend: function () {
                    statusMessage.textContent = "文件读取中，请稍候...";
                    uploadStatus.style.display = "block";
                },
                success: function (data) {
                    if (data.status === 0) {
                        reminder_msg.innerHTML = data.msg;
                        hg_file.innerHTML = data.filename;
                        $('#hg_file').attr('data-value', data.filename);
                    } else {
                        reminder_msg.innerHTML = 'Reminder: ' + data.msg;
                    }
                    uploadStatus.style.display = "none";
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reminder_msg.innerHTML = 'Reminder: ' + errorThrown;
                    uploadStatus.style.display = "none";
                }
            });
        }

        //创建 host_group
        function create_host_group() {
          reminder_remove()
          var hg_file = document.getElementById("hg_file");
          hg_file.innerHTML = "";

          var reminder_msg = document.getElementById("msg");
          var upload_label = "0";
          var upload_hg_executed = "0";

          var an_master = document.getElementById("an_master").value;

          if (radio1.checked) {
              var selectedHostValues = [];
              // 遍历所有的 option 元素，提取它们的值
              $('#selectedHostOptions option').each(function() {
                selectedHostValues.push($(this).val());
              });
            }
          if (radio3.checked) {
              var selectedValues = [];
              // 遍历所有的 option 元素，提取它们的值
              $('#selectedOptions option').each(function() {
                selectedValues.push($(this).val());
              });
            }
          if (radio2.checked) {
              upload_label = document.querySelector('#hg_file').getAttribute('data-value');
            }

          if (an_hg.checked) {
              upload_hg_executed = "1";
            }

            $.ajax({
                type: "post",
                url: "/create_host_group/",
                dataType: "json",
                data: {
                    input1: $("#input1").val(),
                    input5: $("#input5").val(),
                    input6: $("#input6").val(),
                    selectedValues: selectedValues,
                    selectedHostValues: selectedHostValues,
                    upload_label: upload_label,
                    upload_hg_executed: upload_hg_executed,
                    an_master: an_master,
                },
                complete: function () {
                },
                success: function (data) {
                    if (data.status === 0) {
                        reminder_msg.innerHTML = 'Reminder: ' + data.msg;
                        $('#hostgroupModal').modal('hide');
                        location.reload();
                    } else {

                        reminder_msg.innerHTML = 'Reminder: ' + data.msg;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reminder_msg.innerHTML = 'Reminder: ' + errorThrown;
                }
            });
        }

        // 点击删除按钮时设置确认按钮的
        function get_rowid(button) {
                reminder_remove();
                document.getElementById("hg_msg").innerHTML = "";
                // 设置确认按钮的 data-id 属性
                document.querySelector('#confirmButton').setAttribute('data-id', button.id);
                document.getElementById("hg_msg").innerHTML = button.id;

                // 显示确认框
                $('#confirmModal').modal('show');
        }

        // 点击详情按钮展示信息
        function show_minions(button) {
            document.getElementById("hg_name").innerHTML = button.value;
            $('#dataTable1').DataTable().destroy();
            var table = $('#dataTable1').DataTable({
                searching: true,  // 启用搜索
                paging: true,     // 启用分页
                ordering: true,   // 启用排序
                autoWidth: false, // 禁用自动宽度

            });

            $.ajax({
                type: "post",
                url: "/show_selected_host_group/",
                data: {
                    host_group_name: button.value,
                },
                complete: function () {
                },
                success: function (data) {
                    table.clear();
                    const data_object = JSON.parse(data.selected_host_group);
                    data_object.forEach(function(each) {
                        if (each.minion_name === undefined) {
                            table.row.add([
                                each.host_group_name__name,
                                each.salt_name__name
                            ]);
                        } else {
                            table.row.add([
                                each.host_group_name__name,
                                each.minion_name
                            ]);
                        }

                    });
                    table.draw();
                },
            });

            $('#minionModal').modal('show');
        }

        // 定义一个函数来处理填充 selected
        function populateSelectedOptions(data, selected, available) {
            const selectedValues = data || [];

            // 获取 selectedOptions and availableOptions 元素
            const selectedOptions = document.getElementById(selected);
            const availableOptions = document.getElementById(available);

            const options = availableOptions.querySelectorAll('option');
            options.forEach(option => {
                option.hidden = false; // 恢复所有选项
            });

            // 清空现有的选项
            selectedOptions.innerHTML = '';

            // 填充 selectedOptions
            for (const [id, name] of Object.entries(selectedValues)) {
                try {
                    const optionElement = document.createElement('option');
                    optionElement.value = name.id;
                    optionElement.textContent = name.name;

                    selectedOptions.appendChild(optionElement);
                    availableOptions.querySelector(`option[value="${name.id}"]`).hidden=true;
                } catch (error) {
                }

            }
        }

        // 编辑按钮时填充内容
        function get_rowText(button) {
            const rowId = button.getAttribute('data-row-id');
            const row = document.getElementById(rowId);
            const hg_name = row.querySelector('td:nth-child(1)').textContent;
            const hg_des = row.querySelector('td:nth-child(2)').textContent;

            document.querySelector('#input1').value=hg_name;
            document.querySelector('#input5').value=hg_des;
            document.querySelector('#input6').value=rowId;
            document.getElementById('radio2').style.display="none";
            document.getElementById('radio2Label').style.display="none";
            document.getElementById('fileUploadDiv').style.display="none";
            reminder_remove();
            document.getElementById("hg_file").innerHTML = "";

            $.ajax({
                type: "post",
                url: "/show_selected_host_group/",
                data: {
                    host_group_name: button.value,
                },
                complete: function () {
                },
                success: function (data) {
                    const radio1 = document.getElementById("radio1");
                    const multiHostSelect = document.getElementById("multiHostSelect");
                    const radio3 = document.getElementById("radio3");
                    const multiSelect = document.getElementById("multiSelect");
                    if (data.selected_minions_salts_list.type === 1) {
                        $('#availableHostOptions option').show();
                        radio1.checked=true;
                        radio3.checked=false;
                        radio1.disabled = false;
                        radio3.disabled = false;
                        multiHostSelect.style.display = "block";
                        multiSelect.style.display = "none";
                        populateSelectedOptions(data.selected_minions_salts_list.content, "selectedHostOptions", "availableHostOptions");
                    } else if (data.selected_minions_salts_list.type === 2) {
                        $('#availableHostOptions option').hide();
                        radio1.checked=true;
                        radio3.checked=false;
                        radio1.disabled = true;
                        radio3.disabled = true;
                        multiHostSelect.style.display = "block";
                        multiSelect.style.display = "none";
                        populateSelectedOptions(data.selected_minions_salts_list.content, "selectedHostOptions", "availableHostOptions");
                    } else {
                        radio3.checked=true;
                        radio1.checked=false;
                        radio1.disabled = false;
                        radio3.disabled = false;
                        multiSelect.style.display = "block";
                        multiHostSelect.style.display = "none";
                        populateSelectedOptions(data.selected_minions_salts_list.content, "selectedOptions", "availableOptions");
                    }
                },
            });

            // 显示确认框
            $('#hostgroupModal').modal('show');
        };

        // 添加时清空内容
        function clear_rowText() {
                reminder_remove();
                document.querySelector('#input1').value="";
                document.querySelector('#input5').value="";
                document.querySelector('#input6').value="";
                document.getElementById('radio2').style.display="";
                document.getElementById('radio2Label').style.display="";

                // 显示确认框
                $('#hostgroupModal').modal('show');
            };

        //删除主机分组
        function del_host_group() {
            var reminder_msg = document.getElementById("confirm_msg");
            $.ajax({
                type: "post",
                url: "/del_host_group/",
                dataType: "json",
                data: {
                    host_group_name: document.querySelector('#confirmButton').getAttribute('data-id'),
                },
                complete: function () {
                },
                success: function (data) {
                    if (data.status === 0) {
                        reminder_msg.innerHTML = 'Reminder: ' + data.msg;
                        location.reload();
                    } else {
                        reminder_msg.innerHTML = 'Reminder: ' + data.msg;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reminder_msg.innerHTML = 'Reminder: ' + errorThrown;
                }
            });
        }

        //搜索可用主机
        function search_host() {
            var reminder_msg = document.getElementById("msg");
            reminder_remove();

            $.ajax({
                type: "post",
                url: "/search_available_host/",
                dataType: "json",
                data: {
                    searchHostInput: $("#searchHostInput").val(),
                },
                complete: function () {
                },
                success: function (data) {
                    if (data.status === 0) {
                        const search_hosts = data.content;
                        const availableHostOptions = document.getElementById('availableHostOptions');
                        availableHostOptions.innerHTML = '';
                        search_hosts.forEach(function(item, index) {
                            const optionElement = document.createElement('option');
                            optionElement.value = item["id"];
                            optionElement.textContent = item["name"];
                            availableHostOptions.appendChild(optionElement);
                        });

                    } else {
                        reminder_msg.innerHTML = 'Reminder: ' + data.msg;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reminder_msg.innerHTML = 'Reminder: ' + errorThrown;
                }
            });
        }

        //搜索已选主机
        function search_selected_host() {
            var searchValue = document.getElementById("searchSelectedHostInput").value.trim().toLowerCase();
            var selectedHostOptions = document.getElementById("selectedHostOptions");
            var options = selectedHostOptions.options;

            // 遍历选项进行筛选
            for (var i = 0; i < options.length; i++) {
                var optionText = options[i].text.toLowerCase();

                if (searchValue === "" || optionText.includes(searchValue)) {
                    options[i].style.display = ""; // 显示匹配项
                } else {
                    options[i].style.display = "none"; // 隐藏不匹配项
                }
            }
        }
    </script>
{% endblock %}